package com.lin.java.tool.file.service.chain;

import cn.hutool.core.lang.UUID;
import com.lin.java.tool.file.dao.po.SysFileConfigEntity;
import com.lin.java.tool.file.model.FileRecord;
import com.lin.java.tool.general.enums.PlatformEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author: linjiang
 * @date: 2025/1/21
 * 本地文件链
 */
@Slf4j
public class LocalFileChain extends AbstractFileChain {


    public LocalFileChain() {
        super(null, PlatformEnum.LOCAL);
    }

    @Override
    public FileRecord uploadOss(MultipartFile file, SysFileConfigEntity fileConfig) throws IOException {
        log.info("本地文件上传。。。。。。。。。。。。");
        // 生成随机名称
        String fileName = file.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(fileName);
        String newFilename = UUID.fastUUID().toString(true) + "." + suffix;

        // 上传文件
        String fullPath = fullPath(fileConfig.getBucket()) + newFilename;
        File ff = new File(fullPath);
        FileUtils.copyInputStreamToFile(file.getInputStream(), ff);

        // 封装数据
        return FileRecord.builder()
                .platform(platform)
                .bucket(fileConfig.getBucket())
                .path(fullPath)
                .originFileName(fileName)
                .suffix(suffix)
                .size(file.getSize())
                .build();
    }

    @Override
    protected InputStream downloadOss(FileRecord fileReord, SysFileConfigEntity config) throws IOException {
        String filePath = fileReord.getPath();
        File file = new File(filePath);
        if (!file.exists()) {
            log.error("本地文件不存在：{}", filePath);
            return null;
        }

        return new FileInputStream(file);
    }
}
